/**
 *   Copyright 2008 Alexey Vishentsev
 *
 *   Licensed under the Apache License, Version 2.0 (the &quot;License&quot;);
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
 * 
 */

package com.gwtspreadsheetinput.gwt.client;


import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NodeList;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.Grid;
import com.google.gwt.user.client.ui.HTMLTable;

public class Util {
	
	public static void getElementOffset(Element parent,Element child, int[] result){
		result[0] = 0;
		result[1] = 0;
		int x = 0;
		int y = 0;
		for (Element elem = child; elem != null ;elem = elem.getOffsetParent()) {
			if (!parent.isOrHasChild(elem)) {
				break;
			}
			result[0] += x;
			result[1] += y;
			x = elem.getOffsetLeft() - elem.getScrollLeft();
			y = elem.getOffsetTop() - elem.getScrollTop();
		}
	}
	
	/**
	 *  This method seem does not work 
	 **/
	public static void addColStyle(HTMLTable table, int col, String name, String val){
		Element tableElement = table.getElement();
		NodeList<Element> colGroupList = tableElement.getElementsByTagName("colgroup");
		if (colGroupList != null && colGroupList.getLength() > 0) {
			Element colgroup = colGroupList.getItem(0);
			if (DOM.getChildCount((com.google.gwt.user.client.Element) colgroup)>col) {
				Element colElement = DOM.getChild((com.google.gwt.user.client.Element) colgroup, col);
				DOM.setStyleAttribute((com.google.gwt.user.client.Element) colElement, name, val);
			}
		}
		
	}
	
	public static void getSelecitonRectangle(Element parent, Grid table, 
			int row, int col, int[] result) {
		
		Element cellElement = table.getCellFormatter().getElement(row, col);
		Util.getElementOffset(parent, cellElement, result);
		result[0] = result[0];
		result[1] = result[1];
		result[2] = cellElement.getOffsetWidth();
		result[3] = cellElement.getOffsetHeight();
	}

}
